package com.hanserwei.community.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.format.DateTimeFormatter;

/**
 * Jackson 日期时间格式化配置类
 */
@Configuration
public class JacksonConfig {

    // 定义常用的日期时间格式
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String TIME_FORMAT = "HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            // 设置 LocalDateTime 的序列化和反序列化格式
            DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
            builder.serializerByType(java.time.LocalDateTime.class, new LocalDateTimeSerializer(localDateTimeFormatter));
            builder.deserializerByType(java.time.LocalDateTime.class, new LocalDateTimeDeserializer(localDateTimeFormatter));

            // 设置 LocalDate 的序列化和反序列化格式
            DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
            builder.serializerByType(java.time.LocalDate.class, new LocalDateSerializer(localDateFormatter));
            builder.deserializerByType(java.time.LocalDate.class, new LocalDateDeserializer(localDateFormatter));

            // 设置 LocalTime 的序列化和反序列化格式
            DateTimeFormatter localTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT);
            builder.serializerByType(java.time.LocalTime.class, new LocalTimeSerializer(localTimeFormatter));
            builder.deserializerByType(java.time.LocalTime.class, new LocalTimeDeserializer(localTimeFormatter));

            // 可选：禁用将日期作为时间戳写入（更推荐的字符串格式）
             builder.featuresToDisable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

            // 可选：设置 java.util.Date 的全局格式（如果项目仍在使用）
             builder.simpleDateFormat(DATE_TIME_FORMAT);
        };
    }
}